const express = require('express')
const md5 = require('md5')
const tokenManger = require('../utils/tokenManger')
const { adminLogin, verifyToken } = require('../db/crud/loginFn')
const { updateAdmin, logoutAdmin } = require('../db/crud/adminFn')

const router = express.Router()

router.post('/login', async (req, res) => {
  const { username, password } = req.fields
  try {
    const admin = await adminLogin(
      { username, password: md5(password) },
      { password: 0, token: 0 }
    )
    const token = tokenManger.jwtEncode(admin._id)
    await updateAdmin(admin._id, token)
    res.send({ success: true, token, admin })
  } catch (error) {
    res.send({
      success: false,
      msg: '网络错误,请稍后再试',
    })
  }
})
router.post('/verifyToken', async (req, res) => {
  const token = req.get('authorization')
  const admin = await verifyToken(token)
  if (admin) {
    const result = tokenManger.jwtDecode(admin.token)
    if (Date.now() < result.expires) {
      res.send({ success: true })
    } else {
      res.send({ success: false, msg: '登录失效,请重新登录' })
    }
  } else {
    res.send({ success: false, msg: '登录失效,请重新登录' })
  }
})
router.post('/logout', async (req, res) => {
  const { id } = req.fields
  try {
    await logoutAdmin(id)
    res.send({ success: true, msg: '退出成功' })
  } catch (error) {
    res.send({ success: false, msg: '退出失败' })
  }
})

module.exports = router
